//注意js文件放在html文档下部
//注意这里因为要抓区body，所以写在这里
document.body.style.height = document.documentElement.clientHeight + 'px';
document.body.style.width = document.documentElement.clientWidth + 'px';
var bH = document.documentElement.clientHeight;
var bW = document.documentElement.clientWidth;
show('welcome');
setTimeout(function(){
	show('login');
},5000);

//回首页按钮
var backFs = getElesByClassName(document.body,'back');
for(var i=0;i<backFs.length;i++){
	bindEvent(backFs[i],'touchend',function(){
		show('index');
	})
}

//定义一个函数，判断显示哪个页面，哪个页面显示，其余隐藏
//传入id即可
function show(id){
	var obj = document.body.getElementsByTagName('section');
	for(var i=0;i<obj.length;i++){
		obj[i].style.display='none';
	}
	$(id).style.display= 'block';
	//执行此id函数
	if(typeof(eval(id)) == 'function'){
			eval(id)();
	}

}
/*******************************************/
var DOMAIN 		= 'http://192.168.0.108:8082';
var WSURI       = 'ws://192.168.0.108:6070';
var TOKEN  		= 'ichat-secret';
var UID    		= 'ichat-uid';
var UNAME  		= 'ichat-uname';
var HEADPHOTO 	= 'ichat-headPhoto';
/****************************************/
//进入聊天室标记
var INCHAT 		= 'ichat-in-chat';
var INTYPE      = 'ichat-in-type';
var INTID       = 'ichat-in-t-id';
var INTHP       = 'ichat-in-t-headphoto';
//聊天对象
var CHAT_ME     = 1;
var CHAT_OPPO   = 2;
//消息类型
var TYPE_P2P    = 1;
var TYPE_P2G    = 2;
var TYPE_SYSTEM = 3;
/****************API************************/
var API_SUCCESS_CODE = 99999;
var API_LOGIN_SUBMIT = '/i-chat/user/login';
var API_INDEX_CHAT   = '/i-chat/user/chat-list';
var API_INDEX_FRIEND = '/i-chat/user/friend-list';
var API_INDEX_LOGOUT = '/i-chat/user/logout';
/******************************************/
function checkSecret()
{

}
function login()
{
	if (window.localStorage) {
		Storage = window.localStorage;
	} else {
		alert('您的浏览器暂不支持iChat服务');
		return false;
	}
	//Storage.setItem(TOKEN,'bacdef');
	//alert(Storage.removeItem(TOKEN));
	//Storage.clear();
	if (Storage.getItem(TOKEN)) {
		show('index');
	} else {
		$('login').innerHTML = '';
		var login = "<div class='login-name'>用户:&nbsp;&nbsp;<input type='text' name='username'></div><div class='login-passwd'>密码:&nbsp;&nbsp;<input type='password' name='password'></div><div class='login-submit'><div class='login-submit-button'>登录</div></div>";
		$('login').innerHTML = login;
	}
	var oSubmitButton = (getElesByClassName($('login'),'login-submit-button'))[0];
	bindEvent(oSubmitButton, 'touchstart', function (ev) {
		addClass(oSubmitButton, 'login-submit-button-touchstart');
	});
	bindEvent(oSubmitButton, 'touchend', function (ev) {
		removeClass(oSubmitButton, 'login-submit-button-touchstart');
		var oInputs = $('login').getElementsByTagName('input');
		var oUser     = oInputs[0];
		var oPassWord = oInputs[1];
		if (oUser.value == '' || oPassWord.value == '') {
			alert('输入不能为空!');
			return;
		}
		var submit = {
			uid : oUser.value,
			passWord : oPassWord.value
		}
		$ajax({
			url      : DOMAIN + API_LOGIN_SUBMIT,
			method   : 'POST',
			data     : submit,
			callback : function ($data) {
				var loginReturn = JSON.parse($data);
				//console.log(loginReturn);
				if (loginReturn['code'] != API_SUCCESS_CODE) {
					alert(loginReturn['data']);
					return;
				}
				Storage.clear();
				Storage.setItem(TOKEN, loginReturn['data']['token']);
				Storage.setItem(UID, loginReturn['data']['uid']);
				Storage.setItem(UNAME, loginReturn['data']['userName']);
				Storage.setItem(HEADPHOTO, loginReturn['data']['headPhoto']);
				show('index');
			}
		})
	});
}

function index()
{
	WS();//websocket长连接
	$('index').innerHTML = '';
	var submit = {
		token : Storage.getItem(TOKEN),
		uid   : Storage.getItem(UID)
	}
	$ajax({
		url      : DOMAIN + API_INDEX_CHAT,
		method   : 'POST',
		data     : submit,
		callback : function ($data) {
			indexChat = JSON.parse($data);
			var indexShow = '';
			console.log(indexChat);
			if (indexChat['code'] == API_SUCCESS_CODE) {
				var data      = indexChat['data'];
				if (data.length > 0) {
					//index部分
					var first     = "<div class='index-object'><div class='index-photo'><img src='";
					//img/welcome-logo.png
					var second    = "'></div><div class='index-dialogue'><div class='index-name'>";
					//张小凡
					var third     = "</div><div class='index-message'>";
					//张小凡:你明天去哪里...
					var forth     = "</div></div></div>";
					
					for (var i in data) {
						indexShow = indexShow + first + DOMAIN + data[i]['user']['headPhoto'] + second + data[i]['user']['userName'] + third + data[i]['user']['userName'] + ' : ' + data[i]['message'][0]['msg'] + forth;
					}
				}
			}
			var tab = "<div class='set-total'><div class='set-chat'><img src='img/set-chat.ico'></div><div class='set-friend'><img src='img/set-friend.ico'></div><div class='set-set'><img src='img/set-set.ico'></div></div>";
			$('index').innerHTML = indexShow + tab;
			//绑定事件
			index_friend_set_bind($('index'));
			var oIndexList = getElesByClassName($('index'), 'index-object');
			console.log(oIndexList);
			for (var j = 0; j < oIndexList.length; ++j) {
				var oIndex = oIndexList[j];
				oIndex.setAttribute('num', j);
				oIndex.setAttribute('type', data[j]['message'][0]['type']);
				oIndex.setAttribute('tid', data[j]['uid']);
				oIndex.onclick = function () {
					Storage.setItem(INCHAT, this.getAttribute('num'));
					Storage.setItem(INTYPE, this.getAttribute('type'));
					Storage.setItem(INTID, this.getAttribute('tid'));
					index_chat();
					show('chat');
				}
			}
		}
	});
}
function index_friend_set_bind(node)
{
	var oChat   = getElesByClassName(node, 'set-chat')[0];
	var oFriend = getElesByClassName(node, 'set-friend')[0];
	var oSet    = getElesByClassName(node, 'set-set')[0];
	bindEvent(oChat, 'touchstart', function(ev){
		oChat.style.background = 'rgb(253,192,231)';
	})
	bindEvent(oChat, 'touchend', function(ev){
		show('index');
	})
	bindEvent(oFriend, 'touchstart', function(ev){
		oFriend.style.background = 'rgb(253,192,231)';
	})
	bindEvent(oFriend, 'touchend', function(ev){
		show('friend');
	})
	bindEvent(oSet, 'touchstart', function(ev){
		oSet.style.background = 'rgb(253,192,231)';
	})
	bindEvent(oSet, 'touchend', function(ev){
		show('user');
	})
}

function chat()
{
	// $('chat').innerHTML = '';
	// var i = Storage.getItem(INCHAT);
	// Storage.removeItem(INCHAT);
	// var data = indexChat['data'];
	// for (var j in data[i]['message']) {
	// 	chat_addMsg(data[i]['user']['headPhoto'], data[i]['message'][j]['msg'], CHAT_OPPO)
	// }
	var button = "<div class='chat-say'><input class='chat-input' type='text'><div class='chat-send'><div class='chat-send-word'>发送</div></div></div>";
	var back   = "<button class='back'>回首页</button>";
	$('chat').innerHTML = $('chat').innerHTML + button + back;
	var oSend = getElesByClassName($('chat'), 'chat-send-word')[0];
	oSend.onclick = chat_send;
	//标记类型
	var oInput = getElesByClassName($('chat'), 'chat-input')[0];
	oInput.setAttribute('msgType', Storage.getItem(INTYPE));
	oInput.setAttribute('tid', Storage.getItem(INTID));
	oInput.setAttribute('tphoto', Storage.getItem(INTHP));
	Storage.removeItem(INTYPE);
	Storage.removeItem(INTID);
	Storage.removeItem(INTHP);
	//绑定事件
	getElesByClassName($('chat'), 'back')[0].onclick = function() {
		show('index');
	}
}

function index_chat()
{
	$('chat').innerHTML = '';
	var i = Storage.getItem(INCHAT);
	Storage.removeItem(INCHAT);
	var data = indexChat['data'];
	Storage.setItem(INTHP, data[i]['user']['headPhoto']);
	for (var j in data[i]['message']) {
		chat_addMsg(data[i]['user']['headPhoto'], data[i]['message'][j]['msg'], CHAT_OPPO)
	}
}

function friend_chat()
{
	$('chat').innerHTML = '';
}

function chat_send()
{
	var oInput   = getElesByClassName($('chat'), 'chat-input')[0];
	var msgType  = oInput.getAttribute('msgType');
	var tid      = oInput.getAttribute('tid');
	if (!oInput.value) {
		alert('消息不能为空!');
		return;
	}
	chat_addMsg(Storage.getItem(HEADPHOTO), oInput.value, CHAT_ME);
	var message = {
		uid  : Storage.getItem(UID),
		tid  : tid,
		type : msgType,
		msg  : oInput.value
	};
	websocket.send(JSON.stringify(message));
	oInput.value = '';
	oInput.focus();
}

function chat_addMsg(headPhoto, msg, type)
{
	switch (type) {
		case CHAT_ME :
			var meOne = '<div class="chat-user"><div class="chat-me"><div class="chat-photo-me"><img src="';
			//img/gir2.jpg
			var meTwo = '"></div><div class="chat-words-me">';
			//张小凡:你明天去哪里......你明天去哪里...
			var meThree = '</div></div></div>';
			var message  = meOne + DOMAIN + headPhoto + meTwo + msg + meThree;
			break;
		case CHAT_OPPO :
			//chat 部分
			var oppoOne   = "<div class='chat-user'><div class='chat-oppo'><div class='chat-photo-oppo'><img src='";
			//img/gir2.jpg
			var oppoTwo   = "'></div><div class='chat-words-oppo'>"
			//张小凡:你明天去哪里......你明天去哪里...
			var oppoThree = "</div></div></div>";
			var message  = oppoOne + DOMAIN + headPhoto + oppoTwo + msg + oppoThree;
			break;
	}
	var oList     = strTransferDom(message);
	var oMessage  = oList[0];
	var oChatlist = getElesByClassName($('chat'), 'chat-user');
	if (oChatlist.length < 6) {
		$('chat').insertBefore(oMessage, getElesByClassName($('chat'), 'chat-say')[0]);
	} else {
		$('chat').removeChild(oChatlist[0]);
		$('chat').insertBefore(oMessage, getElesByClassName($('chat'), 'chat-say')[0]);
	}
}

function friend()
{
	$('friend').innerHTML = '';
	var submit = {
		token : Storage.getItem(TOKEN),
		uid   : Storage.getItem(UID)
	}
	$ajax({
		url      : DOMAIN + API_INDEX_FRIEND,
		method   : 'POST',
		data     : submit,
		callback : function ($data) {
			indexFriend = JSON.parse($data);
			if (indexFriend) {
				console.log(indexFriend);
				var data      = indexFriend['data'];

				var first  = "<div class='friend-user'><div class='friend-photo'><img src='";
				//img/gir2.jpg
				var second = "'></div><div class='friend-name'>";
				//张小凡
				var third  = "</div></div>";
				var friendShow = '';
				for (var i in data) {
					friendShow = friendShow + first + DOMAIN + data[i]['headPhoto'] + second + data[i]['userName'] + third;
				}
				var statis = "<div class='friend-num'>共" + data.length + "位联系人</div>";
				var tab = "<div class='set-total'><div class='set-chat'><img src='img/set-chat.ico'></div><div class='set-friend'><img src='img/set-friend.ico'></div><div class='set-set'><img src='img/set-set.ico'></div></div>";
				$('friend').innerHTML = friendShow + statis + tab;
				//绑定事件
				index_friend_set_bind($('friend'));
				var oFriendList = getElesByClassName($('friend'), 'friend-user');
				console.log(oFriendList);
				for (var j = 0; j < oFriendList.length; ++j) {
					var oMake = oFriendList[j];
					//oMake.setAttribute('data', j);
					oMake.setAttribute('type', TYPE_P2P);
					oMake.setAttribute('tid', data[j]['uid']);
					oMake.setAttribute('tphoto',  data[j]['headPhoto']);
					oMake.onclick = function () {
						Storage.setItem(INTYPE, this.getAttribute('type'));
						Storage.setItem(INTID, this.getAttribute('tid'));
						Storage.setItem(INTHP, this.getAttribute('tphoto'));
						friend_chat();
						show('chat');
					} 
				}
			}
		}
	});
}

function user()
{
	$('user').innerHTML = '';
	var first = "<div class='user-base'><div class='user-photo'><img src='";
	//img/gir2.jpg
	var second = "'></div><div class='user-info'><div class='user-name'>";
	//张小凡
	var third  = "</div><div class='user-id'>";
	//18612402834
	var four   = "</div></div></div>";

	//---------模块扩展开始
	var modules = user_modules();
	//---------模块扩展结束
	var tab = "<div class='set-total'><div class='set-chat'><img src='img/set-chat.ico'></div><div class='set-friend'><img src='img/set-friend.ico'></div><div class='set-set'><img src='img/set-set.ico'></div></div>";
	$('user').innerHTML = first + DOMAIN + Storage.getItem(HEADPHOTO) + second + Storage.getItem(UNAME) + third + Storage.getItem(UID) + four + modules + tab;
	index_friend_set_bind($('user'));
	user_event();
}
//设置扩展信息，功能在此处添加
function user_modules()
{
	var logout = "<div class='user-set'><div class='user-logout'>退出登录</div></div>";
	//var addFriend = '';
	return logout; // logout + addFriend
}
//设置扩展事件
function user_event()
{
	user_logout();
}

function user_logout()
{
	var oLogout = getElesByClassName($('user'), 'user-logout')[0];
	bindEvent(oLogout, 'touchstart', function (ev){
		oLogout.style.background = 'rgb(173,145,232)';
	})
	bindEvent(oLogout, 'touchend', function (ev){
		var submit = {
			token : Storage.getItem(TOKEN)
		}
		$ajax({
			url    : DOMAIN + API_INDEX_LOGOUT,
			method : 'POST',
			data   : submit,
			callback : function(data) {
				var returnData = JSON.parse(data);
				if (returnData['code'] != API_SUCCESS_CODE){
					alert(returnData['data']);
					return;
				}
				Storage.clear();
				websocket.onclose();
				show('login');
			}
		});
		

	})
}
//webSocket长连接
function WS()
{
	if (typeof(websocket) == 'undefined') {
		websocket = new WebSocket(WSURI);
		console.log('first connect webSocket');
	} else {
		console.log('has connected!');
	}
	websocket.onopen = function(evt) { 
	    console.log('websocket open now');
	    var identity = {
			uid  : Storage.getItem(UID),
			type : TYPE_SYSTEM,
			msg  : '新成员登录啦!'
		}
	    websocket.send(JSON.stringify(identity));
	}; 
	websocket.onclose = function(evt) { 
	    console.log('websocket close now');
	}; 
	websocket.onmessage = function(evt) {
		var data = JSON.parse(evt.data);
		console.log(data);
		var tphoto = getElesByClassName($('chat'), 'chat-input')[0].getAttribute('tphoto');
	    chat_addMsg(tphoto, data['msg'], CHAT_OPPO);
	  
	}; 
	websocket.onerror = function(evt) { 
	    console.log('websocket error:'); 
	    console.log(evt.data); 
	}; 
}  

